<template>
    <div class="waiting-query">
        <!-- 导航栏 -->
        <van-nav-bar title="候诊查询" left-arrow @click-left="goBack" />

        <!-- 主要内容区域 -->
        <div class="content">
            <!-- 患者信息卡片 -->
            <div class="patient-card">
                <div class="patient-info">
                    <div class="patient-name">
                        {{ currentPatient.name }}
                        <van-tag v-if="currentPatient.relationship" type="primary">
                            {{ currentPatient.relationship }}
                        </van-tag>
                    </div>
                    <div class="patient-id">{{ maskedIdCard }}</div>
                </div>
                <div class="switch-patient" @click="showPatientSelector">
                    <van-icon name="arrow" />
                    <span>切换就诊人</span>
                </div>
            </div>

            <!-- 预约详情 -->
            <div class="appointment-details">
                <div class="detail-item">
                    <span class="label">就诊科室</span>
                    <span class="value">{{ appointmentInfo.department }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">医生</span>
                    <span class="value">{{ appointmentInfo.doctorName }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">我的序号</span>
                    <span class="value">{{ appointmentInfo.queueNumber }}</span>
                </div>
            </div>

            <!-- 排队状态 -->
            <div class="queue-status">
                <div class="queue-circle" :class="{ 'urgent': waitingCount === 1 }">
                    <div class="queue-label">前方排队人数</div>
                    <div class="queue-number">{{ waitingCount }}</div>
                </div>
            </div>
        </div>

        <!-- 底部更新按钮 -->
        <div class="footer">
            <button class="update-btn" @click="updateWaitingStatus" :disabled="isUpdating">
                {{ isUpdating ? '更新中...' : '更新' }}
            </button>
        </div>

        <!-- 患者选择器 -->
        <van-popup v-model:show="showSelector" position="bottom" round>
            <div class="patient-list-popup">
                <div class="popup-header">
                    <h3>选择就诊人</h3>
                    <van-icon name="cross" @click="hidePatientSelector" />
                </div>
                <van-list>
                    <van-cell
                        v-for="patient in patientList"
                        :key="patient.patientId"
                        :title="patient.name"
                        :label="patient.relationship"
                        :value="patient.idCardNum.substring(0, 3) + '****' + patient.idCardNum.substring(patient.idCardNum.length - 5)"
                        @click="selectPatient(patient)"
                    />
                </van-list>
            </div>
        </van-popup>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { api } from '@/api/index'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 接口定义
interface Patient {
    patientId: number
    name: string
    idCardNum: string
    relationship: string
}

interface AppointmentInfo {
    department: string
    doctorName: string
    queueNumber: string
    departmentId?: number
    doctorId?: number
}

interface WaitingStatus {
    waitingCount: number
    currentNumber: string
    estimatedTime?: string
}

// 响应式数据
const currentPatient = ref<Patient>({
    patientId: 0,
    name: '',
    idCardNum: '',
    relationship: ''
})

const appointmentInfo = ref<AppointmentInfo>({
    department: '',
    doctorName: '',
    queueNumber: ''
})

const waitingCount = ref<number>(0)
const isUpdating = ref<boolean>(false)
const showSelector = ref<boolean>(false)
const patientList = ref<Patient[]>([])
const isLoading = ref<boolean>(true)
const initialWaitingCount = ref<number>(0) // 记录初始排队人数

// 计算属性
const maskedIdCard = computed(() => {
    const idCard = currentPatient.value.idCardNum
    if (idCard.length > 8) {
        return idCard.substring(0, 3) + '****' + idCard.substring(idCard.length - 5)
    }
    return idCard
})

// 方法
const goBack = () => {
    router.go(-1)
}

const showPatientSelector = () => {
    showSelector.value = true
    loadPatientList()
}

const hidePatientSelector = () => {
    showSelector.value = false
}

const selectPatient = (patient: Patient) => {
    currentPatient.value = patient
    hidePatientSelector()
    // 重置排队人数
    waitingCount.value = 8
    initialWaitingCount.value = 8
    // 重新加载该患者的预约信息
    loadAppointmentInfo()
}

const loadPatientList = async () => {
    try {
        const response = await api.getPatients()
        if (response.code === 200) {
            patientList.value = response.data
            // 如果没有当前患者，选择第一个患者
            if (currentPatient.value.patientId === 0 && response.data.length > 0) {
                currentPatient.value = response.data[0]
                await loadAppointmentInfo()
            }
        }
    } catch (error) {
        console.error('加载患者列表失败:', error)
        ElMessage.error('加载患者列表失败')
        // 使用模拟数据
        patientList.value = [
            {
                patientId: 1,
                name: '蒋峰',
                idCardNum: '622***********0909',
                relationship: '本人'
            }
        ]
        currentPatient.value = patientList.value[0]
        await loadAppointmentInfo()
    }
}

const loadAppointmentInfo = async () => {
    try {
        // 获取当前患者的预约记录
        const response = await api.getAppointmentRecordsByPatient(currentPatient.value.patientId)
        if (response.code === 200 && response.data.length > 0) {
            const latestAppointment = response.data[0]
            appointmentInfo.value = {
                department: latestAppointment.department,
                doctorName: latestAppointment.doctorName,
                queueNumber: latestAppointment.appointmentId.toString(),
                departmentId: latestAppointment.departmentId,
                doctorId: latestAppointment.doctorId
            }
            // 加载候诊状态
            // await updateWaitingStatus() // 注释掉，避免初始化时就调用更新
            waitingCount.value = 8
            initialWaitingCount.value = 8
        } else {
            // 使用模拟数据
            appointmentInfo.value = {
                department: '消化内科-门诊3楼东区501',
                doctorName: '赵马',
                queueNumber: '110',
                departmentId: 1,
                doctorId: 1
            }
            waitingCount.value = 8
            initialWaitingCount.value = 8
        }
    } catch (error) {
        console.error('加载预约信息失败:', error)
        ElMessage.error('加载预约信息失败')
        // 使用模拟数据
        appointmentInfo.value = {
            department: '消化内科-门诊3楼东区501',
            doctorName: '赵马',
            queueNumber: '110',
            departmentId: 1,
            doctorId: 1
        }
        waitingCount.value = 8
        initialWaitingCount.value = 8
    } finally {
        isLoading.value = false
    }
}

const updateWaitingStatus = async () => {
    if (isUpdating.value) return
    
    isUpdating.value = true
    try {
        // 调用候诊查询接口
        const response = await api.getWaitingQueueStatus(
            appointmentInfo.value.departmentId,
            appointmentInfo.value.doctorId
        )
        
        if (response.code === 200) {
            const status: WaitingStatus = response.data
            // 如果API返回的数据有效，使用API数据，否则使用递减逻辑
            if (status.waitingCount !== undefined && status.waitingCount >= 0) {
                waitingCount.value = status.waitingCount
                ElMessage.success('更新成功')
            } else {
                // API数据无效，使用递减逻辑
                handleWaitingCountDecrease()
            }
        } else {
            ElMessage.error('更新失败')
        }
    } catch (error) {
        console.error('更新候诊状态失败:', error)
        // API调用失败，使用递减逻辑
        handleWaitingCountDecrease()
    } finally {
        isUpdating.value = false
    }
}

// 处理排队人数递减逻辑
const handleWaitingCountDecrease = () => {
    if (waitingCount.value > 1) {
        waitingCount.value = waitingCount.value - 1
        ElMessage.success('更新成功')
    } else {
        // 排队人数为1时，提示就诊
        ElMessage({
            message: '该就诊人该就诊了！',
            type: 'warning',
            duration: 3000,
            showClose: true
        })
    }
}

// 生命周期
onMounted(() => {
    // 初始化时加载数据
    loadPatientList()
})
</script>

<style scoped>
.waiting-query {
    min-height: 100vh;
    background-color: #f7f8fa;
}

/* 内容区域 */
.content {
    padding: 0;
}

/* 患者信息卡片 */
.patient-card {
    margin: 16px;
    padding: 16px;
    background-color: white;
    border-radius: 8px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.patient-info {
    flex: 1;
}

.patient-name {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
}

.name {
    font-size: 16px;
    font-weight: 500;
    color: #323233;
}

.patient-id {
    font-size: 14px;
    color: #646566;
}

.switch-patient {
    display: flex;
    align-items: center;
    gap: 4px;
    color: #1989fa;
    font-size: 14px;
    cursor: pointer;
}

/* 预约详情 */
.appointment-details {
    margin: 0 16px 16px;
    background-color: white;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.detail-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;
}

.detail-item:last-child {
    border-bottom: none;
}

.label {
    font-size: 14px;
    color: #666;
}

.value {
    font-size: 14px;
    color: #333;
    font-weight: 500;
}

/* 排队状态 */
.queue-status {
    display: flex;
    justify-content: center;
    margin-bottom: 80px;
}

.queue-circle {
    width: 200px;
    height: 200px;
    background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
    border-radius: 50%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: white;
    box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3);
    transition: all 0.3s ease;
}

.queue-circle.urgent {
    background: linear-gradient(135deg, #ff4444, #ff6666);
    box-shadow: 0 4px 20px rgba(255, 68, 68, 0.5);
    animation: pulse 1.5s infinite;
}

@keyframes pulse {
    0% {
        transform: scale(1);
    }
    50% {
        transform: scale(1.05);
    }
    100% {
        transform: scale(1);
    }
}

.queue-label {
    font-size: 14px;
    margin-bottom: 8px;
    opacity: 0.9;
}

.queue-number {
    font-size: 48px;
    font-weight: bold;
    line-height: 1;
}

/* 底部按钮 */
.footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: white;
    padding: 16px;
    border-top: 1px solid #e0e0e0;
    z-index: 10;
}

.update-btn {
    width: 100%;
    height: 48px;
    background-color: #1976d2;
    color: white;
    border: none;
    border-radius: 8px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: background-color 0.3s;
    pointer-events: auto;
    z-index: 1;
}

.update-btn:hover:not(:disabled) {
    background-color: #1565c0;
}

.update-btn:disabled {
    background-color: #ccc;
    cursor: not-allowed;
}

/* 患者选择器 */
.patient-list-popup {
    padding: 16px;
}

.popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #ebedf0;
}

.popup-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
    color: #323233;
}

/* 响应式设计 */
@media (max-width: 480px) {
    .content {
        padding: 12px;
    }
    
    .nav-bar {
        padding: 8px 12px;
    }
    
    .footer {
        padding: 12px;
    }
    
    .queue-circle {
        width: 160px;
        height: 160px;
    }
    
    .queue-number {
        font-size: 36px;
    }
}
</style>
